﻿using System;
using System.Linq;
using System.Reflection;
using System.Threading;
using log4net;

namespace SopCastRecorder
{
	public class Timer
	{
		private static ILog logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

		private static Timer Timer1 = new Timer();

		private static Thread Thread1;

		private Timer()
		{
		}

		public static void Start()
		{
			Thread1 = new Thread(new ThreadStart(Timer1.NewThreadStart));
			Thread1.Start();
		}

		public static void Stop()
		{
			if (Thread1 == null)
			{
				return;
			}
			Thread1.Abort();
		}

		private void NewThreadStart()
		{
			try
			{
				this.NewThreadStart2();
			}
			catch (ThreadAbortException)
			{
			}
			catch (Exception exception1)
			{
				logger.Error(MethodBase.GetCurrentMethod().Name, exception1);
				Form1.SetErrorStatus();
			}
		}

		private void NewThreadStart2()
		{
			var managers = ScheduleInfoManager.GetScheduleInfoManagers();

			while (true)
			{
				for(var i = 0 ; i < managers.Count() ; i++)
				{
					var manager = managers[i];
					if(manager.Start())
					{
						continue;
					}
					if(manager.Stop())
					{
					}
					if (manager.Status1 == ScheduleInfoManager.Status.Finished)
					{
						managers.Remove(manager);
						i--;
					}
				}

				if (managers.Count() == 0)
				{
					Stop();
					return;
				}
				Thread.Sleep(1000);
			}
		}
	}
}
